import { execSync, spawn, spawnSync } from "child_process";
import { BasePlatform } from "./BasePlatform";
import path from 'path';
import PackUtil from "../utils/PackUtil";
import { ChannelInfo } from "./PlatformConfig";
import { existsSync } from "fs";
export class ByteDance extends BasePlatform {
    public async afterBuildFinish() {
        let channelInfo: ChannelInfo = this.configData.platforms[this.curPackChannel];
        let remoteDir = PackUtil.compareVersion(this.configData.engineVer, "2.4.0") >= 0 ? "remote" : "res";
        let remotepath = path.join(this.outputPath, channelInfo.platform, remoteDir);
        if (existsSync(remotepath) && channelInfo.remoteDir != "") {
            console.log('upload cdn res start');
            let cdnrespath = channelInfo.remoteDir;
            PackUtil.pullCDNRes(cdnrespath);
            PackUtil.moveFiles(remotepath, cdnrespath);
            PackUtil.uploadCDNRes(cdnrespath);
            console.log('upload cdn res finish');
        }
        //login
        let cmd = path.join(__dirname, "../../node_modules/.bin/tma.cmd");
        let returninfo = spawnSync(cmd, ['login-e', `${channelInfo.account}`, `${channelInfo.password}`]);
        if (returninfo.error) {
            console.error("login error：", returninfo.error);
        }
        let upload = spawn(cmd, ['upload', "-v", `${this.version}`, "-c", `autopack-${this.version}-${new Date().toLocaleString()}`, path.join(this.outputPath, "bytedance")]);
        upload.stdout.setEncoding('utf8');
        upload.stdout.on('data', (data) => {
            console.log(data);
        });
        upload.on('error', (err: Error) => {
            console.log(err.message);
        });
        upload.on('exit', (code, sign) => {
            if (code == 0) {
                console.log(`upload ${this.curPackChannel} success!`);
                this.saveBackUpConfig();
                super.afterBuildFinish();
            }else{
                throw Error();
            }
        });
        //上传
        // await super.afterBuildFinish();
    }
}